import axios from 'axios'
import { Toast } from 'vant'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from './tools'
// export const serverUrl = "http://vae5ke.natappfree.cc";
export const serverUrl = 'http://47.104.75.203:8080'
// export const serverUrl = "http://localhost:1337";

const instance = axios.create({
  baseURL: serverUrl, // 请求的基础地址
  timeout: 5000 // 请求超时时间
})

// Add a request interceptor
// 全局请求拦截，发起网络请求之前执行
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    NProgress.start() // 显示loading
    config.headers.token = getToken()
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
// 全局响应拦截，网络请求返回之后执行
instance.interceptors.response.use(
  function (response) {
    NProgress.done() // 隐藏loading
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response.data
  },
  function (error) {
    NProgress.done()
    // 此处需要对服务器返回的状态码做特殊处理
    console.dir(error)
    if (error.response?.status == 401) {
      Toast.fail('请先登录')
      window.location.href = '/#/login' // 跳转到登录页
    }
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  }
)

/**
 * 发起一个get请求
 * @param {*} url     地址
 * @param {*} params  url中传递的参数
 * @returns
 */
export const get = (url, params) =>
  instance.get(url, {
    params // 表示url中传递的参数
  })

/**
 * 发起post请求
 * @param {*} url   地址
 * @param {*} data  数据
 * @returns
 */
export const post = (url, data) => instance.post(url, data)

/**
 * 发起put请求
 * @param {*} url   地址
 * @param {*} data  数据
 * @returns
 */
export const put = (url, data) => instance.put(url, data)

/**
 * 发起delete请求
 * @param {*} url
 * @returns
 */
export const del = (url) => instance.delete(url)

export default instance
